import axios from 'axios';

export const BASE_URL = 'http://localhost:5173/api';

// 创建axios实例
const instance = axios.create({
  baseURL: BASE_URL,
  timeout: 5000
});

// 请求拦截器 - 添加token
instance.interceptors.request.use(config => {
  const token = localStorage.getItem('token') || '';
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

// 响应拦截器 - 处理token过期等情况
instance.interceptors.response.use(
  response => response,
  error => {
    if (error.response && error.response.status === 401) {
      // token过期或无效，清除本地存储并跳转到登录页
      localStorage.removeItem('token');
      localStorage.removeItem('userInfo');
      window.location.href = '/login';
    }
    return Promise.reject(error);
  }
);

export default instance;